<template>
  <div class="menu-container">
    <div class="error-msg" v-if="errorMsg">{{ errorMsg }}</div>
    <el-menu class="menu" :default-active="activeIndex" @select="handleSelect">
      <template v-for="menu in menuList" :key="menu.menuId">
        <!-- 如果菜单有子菜单，使用 el-sub-menu 渲染 -->
        <el-sub-menu
            v-if="menu.children && menu.children.length > 0"
            class="el-sub-menu"
            :index="menu.menuId.toString()"
        >
          <template #title>
            <!-- 添加图标 -->
            <!--            <el-icon class="enhanced-icon"><{{ menu.icon }} /></el-icon>-->
            <span>{{ menu.menuName }}</span>
          </template>
          <!-- 渲染子菜单 -->
          <el-menu-item
              v-for="child in menu.children"
              :key="child.menuId"
              :index="child.menuUrl"
          >
            <!-- 添加图标 -->
            <router-link :to="child.menuUrl" class="menu-link">
              {{ child.menuName }}
            </router-link>
          </el-menu-item>
        </el-sub-menu>
        <!-- 如果菜单没有子菜单，直接使用 el-menu-item 渲染 -->
        <el-menu-item
            v-else
            :key="menu.menuId"
            :index="menu.menuUrl"
        >
          <!-- 添加图标 -->
          <!--          <el-icon class="enhanced-icon"><{{ menu.icon }} /></el-icon>-->
          <router-link :to="menu.menuUrl" class="menu-link">
            {{ menu.menuName }}
          </router-link>
        </el-menu-item>
      </template>
    </el-menu>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import http from '@/axios/http';
import { useUserStore } from '@/store/userStore.js';

const errorMsg = ref('');
const menuList = ref([]);
const activeIndex = ref('0');

// 将扁平化数据转换为树形结构
const convertToTree = (flatData) => {
  const map = new Map();
  const treeData = [];

  // 首先将每个菜单项存储到 Map 中，方便后续查找
  flatData.forEach((item) => {
    map.set(item.menuId, { ...item, children: [] });
  });

  // 遍历每个菜单项，将其添加到对应的父菜单下
  flatData.forEach((item) => {
    const parentId = item.parentMenuId || 0;
    const parent = map.get(parentId);
    if (parent) {
      parent.children.push(map.get(item.menuId));
    } else {
      // 如果没有父菜单，说明是顶级菜单，添加到树的根节点
      treeData.push(map.get(item.menuId));
    }
  });

  return treeData;
};

onMounted(() => {
  const userStore = useUserStore();
  const roleid = userStore.getUserrole;

  console.log('user roleid:', roleid);

  http.post('/glsb/getmenus', { roleid })
      .then((res) => {
        const resultmenu = res.data;
        console.log('后端返回结果:', resultmenu);

        if (resultmenu.result === 'success') {
          console.log('返回的菜单数据:', resultmenu.data);
          const treeData = convertToTree(resultmenu.data);
          console.log('转换后的树形数据:', treeData);
          menuList.value = treeData;
        } else {
          console.log(resultmenu.error);
          errorMsg.value = resultmenu.error;
        }
      })
      .catch((error) => {
        console.log('请求出错:', error);
        errorMsg.value = '网络错误，请稍后再试！';
      });
});

const handleSelect = (index) => {
  console.log('Selected menu index:', index);
};
</script>

<style scoped>
/* 容器样式 */
.menu-container {
  background: linear-gradient(180deg, #f5f5f5 0%, #e0e0e0 100%);
  color: #333;
  box-shadow: 8px 0 20px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  padding: 10px;
  width: 250px;
}

/* 菜单整体样式 */
.el-menu {
  background-color: rgba(255, 255, 255, 0.9); /* 更明亮的背景 */
  border-radius: 1px;
  box-shadow: 0 20px 10px rgba(0, 0, 0, 0.1); /* 添加内阴影 */
  font-family: 'Inter', 'PingFang SC', 'Microsoft YaHei', sans-serif;
  font-size: 15px;
}

/* 菜单项基础样式 */
.el-menu-item, .el-submenu__title ,.el-sub-menu__title{
  color: #333;
  font-weight: 400;
  border-radius: 10px;
  padding: 10px 40px;
  transition: background-color 0.3s ease, color 0.3s ease;
  font-family: 'Inter', 'PingFang SC', 'Microsoft YaHei', sans-serif;
  font-size: 14px;        /* 原来 14→16 放大 */

}

/* 菜单项悬停样式 */
.el-menu-item:hover, .el-submenu__title:hover {
  background-color: rgba(240, 240, 240, 1); /* 悬停时更亮的背景 */
  color: #2196F3; /* 悬停时文字颜色 */
}

/* 错误信息样式 */
.error-msg {
  color: #F44336;
  font-size: 14px;
  margin-bottom: 10px;
  text-align: center;
}

/* 链接样式 */
.menu-link {
  text-decoration: none;
  color: inherit;
  display: inline-block;
  width: 100%;
}
</style>